

<template>
  <el-dialog
      v-model="dialogVisible"
      title="项目详情"
      :close-on-click-modal="false"
      width="80%"
  >
    <div  v-loading="loading" class="dialog-box">
      <div>
        <div class="dialog-one-title">项目信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称" max-width="300">
            <el-select v-model="projectInfo.projectId"
                       @focus="getprojectOptions"
                       @input="handleInput"
                       filterable
                       placeholder="请选择项目名称">
              <el-option
                  v-for="(item, index) in projectOptions"
                  :key="item.projectId"
                  :label="item.name"
                  :value="item.projectId"
                  @click="() => changeprojectOptions(item)"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="批准经费">{{ turnWanyuan(projectInfo.feeAuthorize) }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ projectInfo.chargerName }}</el-descriptions-item>
          <el-descriptions-item label="所属单位">{{ projectInfo.unitName }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ projectInfo.beginDate }}</el-descriptions-item>
          <el-descriptions-item label="计划完成日期">{{ projectInfo.planEndDate }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div>
        <div class="title-col">调账说明</div>
        <div>1、当前项目是按照入账经费分配经费卡额度。</div>
        <div>2、调账后需保证所有经费卡的入账总额不发生变化。</div>
        <div>3、调账后需保证所有经费卡的每个科目额度之和不超过科目总留校预算。</div>
        <div>4、调账后需保证每张卡的入账总金额等于经费卡入账总额度。</div>
        <div>5、科目额度增加时调整量填写正数，例如+0.2；额度减少时调整量填写负数，例如-0.2；当科目额度调整量为负数时，其绝对值不能大于科目额度结余。</div>
      </div>
      <div>
        <div class="title-col">经费卡入账记录(单位：万元)</div>
        <div>
          <el-descriptions :column="1"  border >
            <el-descriptions-item align="center" label="经费卡负责人">{{ projectInfo.feeChargerName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="经费卡号">{{ projectInfo.feeCardNum }}</el-descriptions-item>
            <el-descriptions-item align="center" label="所属单位（经费卡）">{{ projectInfo.unitName }}</el-descriptions-item>
            <el-descriptions-item align="center" label="累计入账">{{ turnWanyuan(projectInfo.incomeTotal) }}</el-descriptions-item>
<!--            <el-descriptions-item align="center" label="入账结余">{{ turnWanyuan(parseFloat(projectInfo.feeAuthorize) - parseFloat(projectInfo.incomeTotal)) }}</el-descriptions-item>-->
            <el-descriptions-item align="center" label="入账结余">{{ turnWanyuan(calculateBalance())}}</el-descriptions-item>
<!--            <el-descriptions-item align="center" label="调整量">-->
<!--              <el-input-number-->
<!--                  v-model="projectInfo.adjustmentFee"-->
<!--                  :min="0"-->
<!--              ></el-input-number>-->
<!--            </el-descriptions-item>-->
<!--            <el-descriptions-item align="center" label="调整后入账">{{ projectInfo.afterFee }}</el-descriptions-item>-->
          </el-descriptions>
        </div>
        <div>
          <el-table
              :data="treeData"
              border
              row-key="subjectId"
              default-expand-all
              :tree-props="{ children: 'children' }"
          >
            <el-table-column prop="subjectName" label="科目名称">

            </el-table-column>
            <el-table-column prop="subjectFee" label="总预算">
              <template #default="scope">
                {{turnWanyuan(scope.row.subjectFee)}}
              </template>
            </el-table-column>
            <el-table-column prop="allincome" label="累计入账额度">
              <template #default="scope">
                {{turnWanyuan(scope.row.allincome)}}
              </template>
            </el-table-column>
            <el-table-column prop="balance" label="额度结余">
              <template #default="scope">
                {{turnWanyuan(scope.row.balance)}}
              </template>
            </el-table-column>
            <el-table-column prop="budgetFeeChange" label="调整量">
              <template #default="scope">
                <template v-if="!scope.row.children || scope.row.children.length === 0">
                  <el-input-number
                      v-model="scope.row.budgetFeeChange"
                      :disabled="scope.row.subjectFee === 0 || scope.row.subjectFee == '0'"
                      @change="handleInputChange(scope.row)"
                  ></el-input-number>
                </template>
                <template v-else>
                  {{ scope.row.budgetFeeChange }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="afterAmount" label="调整后入账额度">
              <template #default="scope">
                {{turnWanyuan(scope.row.afterAmount)}}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div>
        <el-input v-model="projectInfo.alterreason" type="textarea" placeholder="调账原因"/>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSave">暂存</el-button>
        <el-button type="primary" v-if="!verifyRoleType.iskycgly()" @click="submit">提交</el-button>
        <el-button type="primary" @click="handleSaveAndPass">保存并通过</el-button>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
const loading = ref(false) // 添加加载状态
import { verifyRoleType } from "@/utils/main";
import {ref,computed,watch} from "vue";
import {turnWanyuan} from "../../../utils/money";
import {
  selectVproject,
  getBudgetInfo,
    add,edit,checkproject
} from './../../../api/money/jfdzApi'
import {ElMessage} from "element-plus";
// 计算入账结余
// watch([() => projectInfo.value.feeAuthorize, () => projectInfo.value.incomeTotal], () => {
//   const feeAuthorize = parseFloat(projectInfo.value.feeAuthorize);
//   const incomeTotal = parseFloat(projectInfo.value.incomeTotal);
//   projectInfo.value.entryBalance = (feeAuthorize - incomeTotal).toString();
// });
const calculateBalance = () => {
  const feeAuthorizeStr = projectInfo.value.feeAuthorize;
  const incomeTotalStr = projectInfo.value.incomeTotal;

  // 如果两个值都为空串，直接返回空字符串
  if (feeAuthorizeStr === '' && incomeTotalStr === '') {
    return '';
  }

  const feeAuthorize = isNaN(parseFloat(feeAuthorizeStr)) ? 0 : parseFloat(feeAuthorizeStr);
  const incomeTotal = isNaN(parseFloat(incomeTotalStr)) ? 0 : parseFloat(incomeTotalStr);

  return feeAuthorize - incomeTotal;
};

//获取项目下拉
const getprojectOptions = () => {
  selectVproject({
    pageNum:1,
    pageSize:50,
  })
      .then((res)=>{
        projectOptions.value = res.rows
      })
}
const DialogTop = ref({})
const DialogMid = ref({})

// 初始化数据
const initData = (data, parent = null) => {
  data.forEach(item => {
    item.$parent = parent;
    // 提取 alterationVals 中的数据并转换为数值类型
    const { allincome, allpayout, budgetFeeChange } = item.alterationVals[0];
    item.allincome = Number(allincome);
    item.allpayout = allpayout!== null? Number(allpayout) : null;
    item.budgetFeeChange = budgetFeeChange? Number(budgetFeeChange) : 0;

    // 计算调整后入账额度
    item.afterAmount = item.allincome + item.budgetFeeChange;
    // 计算额度结余
    item.balance = item.subjectFee? Number(item.subjectFee) - item.allincome : 0;

    // 递归处理子节点
    if (item.children && item.children.length > 0) {
      initData(item.children, item);
      // 汇总子节点的累计入账
      item.allincome = item.children.reduce((sum, child) => sum + child.allincome, 0);
      // 汇总子节点的调整量
      item.budgetFeeChange = item.children.reduce((sum, child) => sum + child.budgetFeeChange, 0);
      // 汇总子节点的调整后入账额度
      item.afterAmount = item.children.reduce((sum, child) => sum + child.afterAmount, 0);
      // 重新计算父节点的额度结余
      item.balance = item.subjectFee? Number(item.subjectFee) - item.allincome : 0;
    }
  });
};
const changeprojectOptions = (itemObj) => {
 // console.log(itemObj.projectClass)
  getBudgetInfo({
    projectId:projectInfo.value.projectId,
    projectClass:itemObj.projectClass
  })
      .then((res)=>{
        DialogTop.value = projectOptions.value.find((item) => item.projectId === projectInfo.value.projectId);
        checkproject({projectId: projectInfo.value.projectId})
            .then((res)=>{
              if(res){
                // alert('不能看')
                ElMessage({
                  message: res,
                  type: 'error'
                });
                showContent.value = false
                return;
              }else {
                showContent.value = true
              }
             // if(!(res instanceof Promise)){
             //   const messageMap = {
             //     'cwIncomeClaim': '当前项目有未结束的认领经费，不能进行经费调账！',
             //     'alteration': '当前项目有未结束的调账经费，不能进行经费调账！',
             //     'claimBack': '当前项目有未结束的退回经费，不能进行经费调账！',
             //     'noProBudget': '当前项目没有预算信息，不能进行经费调账！',
             //     'noIncome': '该项目没有到账信息,无法进行经费调账！',
             //   };
             //
             //   if (messageMap[res]) {
             //     ElMessage({
             //       message: messageMap[res],
             //       type: 'error'
             //     });
             //     return;
             //   }
             // }

            })


        DialogMid.value = res.data.amountAlterationVO[0]
        treeData.value = res.data.budgetAmountAlterationVO
         initData(treeData.value)
        // if(res.data.amountAlterationVO.length < 0){
        //   DialogMid.value = res.data.amountAlterationVO[0]
        // }
        Object.assign(projectInfo.value, DialogTop.value, DialogMid.value);


        console.log(treeData.value)

      })
}


// 计算指定字段的总和，根据是否只计算一级数据进行处理
const calculateTotal = (data, field, onlyFirstLevel = false) => {
  let total = 0;
  data.forEach(item => {
    if (typeof item[field] === 'string') {
      total += parseFloat(item[field]);
    } else {
      total += item[field];
    }
    if (!onlyFirstLevel && item.children && item.children.length > 0) {
      total += calculateTotal(item.children, field);
    }
  });
  return total;
};

// 处理输入框的 change 事件
const handleInputChange = (row) => {
  const originalBudgetFeeChange = row.budgetFeeChange;
  const budgetFeeChangeInYuan = row.budgetFeeChange * 10000; // 调整量转换为元
  const afterAmount = row.allincome + budgetFeeChangeInYuan;
  const balance = row.subjectFee? Number(row.subjectFee) - afterAmount : 0;

  // 检查调整后入账额度和额度结余是否为负数
  if (afterAmount < 0) {
    ElMessage({
      message: `科目 ${row.subjectName} 的调整后入账额度不能为负数！`,
      type: 'error'
    });
    row.budgetFeeChange = 0;
    row.afterAmount = row.allincome;
    row.balance = row.subjectFee? Number(row.subjectFee) - row.allincome : 0;
    restoreParentData(row.$parent);
    return;
  }
  if (balance < 0) {
    ElMessage({
      message: `科目 ${row.subjectName} 的额度结余不能为负数！`,
      type: 'error'
    });
    row.budgetFeeChange = 0;
    row.afterAmount = row.allincome;
    row.balance = row.subjectFee? Number(row.subjectFee) - row.allincome : 0;
    restoreParentData(row.$parent);
    return;
  }

  row.afterAmount = afterAmount;
  row.balance = balance;

  // 更新父节点数据
  let currentParent = row.$parent;
  while (currentParent) {
    currentParent.budgetFeeChange = currentParent.children.reduce((sum, child) => sum + child.budgetFeeChange, 0);
    const parentAllIncome = currentParent.children.reduce((sum, child) => sum + child.allincome, 0);
    const parentBudgetFeeChangeInYuan = currentParent.budgetFeeChange * 10000;
    currentParent.afterAmount = parentAllIncome + parentBudgetFeeChangeInYuan;
    currentParent.balance = currentParent.subjectFee? Number(currentParent.subjectFee) - currentParent.afterAmount : 0;
    currentParent = currentParent.$parent;
  }
  console.log(row);
};

// 复原父节点数据
const restoreParentData = (parent) => {
  if (!parent) return;
  parent.budgetFeeChange = parent.children.reduce((sum, child) => sum + child.budgetFeeChange, 0);
  const parentAllIncome = parent.children.reduce((sum, child) => sum + child.allincome, 0);
  const parentBudgetFeeChangeInYuan = parent.budgetFeeChange * 10000;
  parent.afterAmount = parentAllIncome + parentBudgetFeeChangeInYuan;
  parent.balance = parent.subjectFee? Number(parent.subjectFee) - parent.afterAmount : 0;
  restoreParentData(parent.$parent);
};

//所有弹窗内容
// 模拟树形表格数据
const treeData = ref([
  // {
  //   subjectName: '一级科目 1',
  //   totalBudget: '10000', //总预算
  //   accumulatedEntry: '5000',//累计入账额度
  //   balance: '5000',//额度结余
  //   adjustment: 0,//调整量
  //   adjustedEntry: '5000',//调整后入账额度
  //   children: [
  //     {
  //       subjectName: '二级科目 1-1',
  //       totalBudget: '5000',
  //       accumulatedEntry: '2000',
  //       balance: '3000',
  //       adjustment: 0,
  //       adjustedEntry: '2000'
  //     },
  //     {
  //       subjectName: '二级科目 1-2',
  //       totalBudget: '5000',
  //       accumulatedEntry: '3000',
  //       balance: '2000',
  //       adjustment: 0,
  //       adjustedEntry: '3000'
  //     }
  //   ]
  // },
  // {
  //   subjectName: '一级科目 2',
  //   totalBudget: '20000',
  //   accumulatedEntry: '10000',
  //   balance: '10000',
  //   adjustment: 0,
  //   adjustedEntry: '10000'
  // },


  // {
  //   "subjectFee": null,
  //   "upCode": null,
  //   "subjectId": "402881446b4995d8016b49cc67cf0010",
  //   "subjectCode": "Z005201",
  //   "subjectName": "项目直接费用合计",
  //   "alterationVals": [
  //     {
  //       "allincome": "4000000",
  //       "allpayout": null,
  //       "feeCardNum": "Z20250001",
  //       "subjectCode": "Z005201",
  //       "budgetFeeChange": null,
  //       "afterAmount": null
  //     }
  //   ],
  //   "children": [
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67cf0011",
  //       "subjectCode": "Z00520101",
  //       "subjectName": "1、设备费",
  //       "alterationVals": [
  //         {
  //           "allincome": "2100000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520101",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": [
  //         {
  //           "subjectFee": null,
  //           "upCode": "Z00520101",
  //           "subjectId": "402881446b4995d8016b49cc67cf0012",
  //           "subjectCode": "Z0052010101",
  //           "subjectName": "(1)设备购置费",
  //           "alterationVals": [
  //             {
  //               "allincome": "1550000",
  //               "allpayout": null,
  //               "feeCardNum": "Z20250001",
  //               "subjectCode": "Z0052010101",
  //               "budgetFeeChange": null,
  //               "afterAmount": null
  //             }
  //           ],
  //           "children": []
  //         },
  //         {
  //           "subjectFee": null,
  //           "upCode": "Z00520101",
  //           "subjectId": "402881446b4995d8016b49cc67cf0013",
  //           "subjectCode": "Z0052010102",
  //           "subjectName": "(2)设备试制费",
  //           "alterationVals": [
  //             {
  //               "allincome": "450000",
  //               "allpayout": null,
  //               "feeCardNum": "Z20250001",
  //               "subjectCode": "Z0052010102",
  //               "budgetFeeChange": null,
  //               "afterAmount": null
  //             }
  //           ],
  //           "children": []
  //         },
  //         {
  //           "subjectFee": null,
  //           "upCode": "Z00520101",
  //           "subjectId": "402881446b4995d8016b49cc67cf0014",
  //           "subjectCode": "Z0052010103",
  //           "subjectName": "(3)设备改造与租赁费",
  //           "alterationVals": [
  //             {
  //               "allincome": "100000",
  //               "allpayout": null,
  //               "feeCardNum": "Z20250001",
  //               "subjectCode": "Z0052010103",
  //               "budgetFeeChange": null,
  //               "afterAmount": null
  //             }
  //           ],
  //           "children": []
  //         }
  //       ]
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67cf0015",
  //       "subjectCode": "Z00520102",
  //       "subjectName": "2、材料费",
  //       "alterationVals": [
  //         {
  //           "allincome": "500000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520102",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67cf0016",
  //       "subjectCode": "Z00520103",
  //       "subjectName": "3、测试化验加工费",
  //       "alterationVals": [
  //         {
  //           "allincome": "200000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520103",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d00017",
  //       "subjectCode": "Z00520104",
  //       "subjectName": "4、燃料动力费",
  //       "alterationVals": [
  //         {
  //           "allincome": "150000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520104",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d00018",
  //       "subjectCode": "Z00520105",
  //       "subjectName": "5、差旅/会议/国际合作与交流费",
  //       "alterationVals": [
  //         {
  //           "allincome": "200000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520105",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d00019",
  //       "subjectCode": "Z00520106",
  //       "subjectName": "6、出版/文献/信息传播/知识产权事务费",
  //       "alterationVals": [
  //         {
  //           "allincome": "250000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520106",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d0001a",
  //       "subjectCode": "Z00520107",
  //       "subjectName": "7、劳务费",
  //       "alterationVals": [
  //         {
  //           "allincome": "200000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520107",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d0001b",
  //       "subjectCode": "Z00520108",
  //       "subjectName": "8、专家咨询费",
  //       "alterationVals": [
  //         {
  //           "allincome": "300000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520108",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     },
  //     {
  //       "subjectFee": null,
  //       "upCode": "Z005201",
  //       "subjectId": "402881446b4995d8016b49cc67d0001c",
  //       "subjectCode": "Z00520109",
  //       "subjectName": "9、其他支出",
  //       "alterationVals": [
  //         {
  //           "allincome": "100000",
  //           "allpayout": null,
  //           "feeCardNum": "Z20250001",
  //           "subjectCode": "Z00520109",
  //           "budgetFeeChange": null,
  //           "afterAmount": null
  //         }
  //       ],
  //       "children": []
  //     }
  //   ]
  // },
  // {
  //   "subjectFee": null,
  //   "upCode": null,
  //   "subjectId": "outboundCode",
  //   "subjectCode": "outboundCode",
  //   "subjectName": "转拨费",
  //   "alterationVals": [
  //     {
  //       "allincome": "1000000",
  //       "allpayout": null,
  //       "feeCardNum": "Z20250001",
  //       "subjectCode": "outboundCode",
  //       "budgetFeeChange": null,
  //       "afterAmount": null
  //     }
  //   ],
  //   "children": []
  // }



]);
// 项目名称下拉框选项
const projectOptions = ref([]);
const projectInfo = ref({
  projectId: '',//项目下拉id
  projectName: '', //项目，名称
  feeAuthorize: '',
  chargerName: '',//负责人
  unitName: '', //所属单位
  beginDate: '',//开始事件
  planEndDate: '',//计划结束事件
  feeChargerName: '',//负责人名称
  feeCardNum: '',//经费卡号
  incomeTotal: '',//累计入账
  entryBalance: '',
  adjustmentFee: '0',//调整量
  afterFee: '',
  alterreason:'',
   //对应头部基本信息
  // account: "9527"
  // beginDate: "2025-01-01"
  // chargerCode: "2c97a3549424ba180194251665790001"
  // chargerName: "老学生"
  // chargerUnitId: null
  // chargerUnitName: null
  // code: "纵20250001"
  // feeAuthorize: "5000000"
  // id: "2c97a3549424ba18019425207dd5000c"
  // name: "基于CRISPR-Cas9技术的基因编辑在遗传性疾病治疗中的应用研究111444444"
  // outFee: null
  // planEndDate: "2027-01-01"
  // projectClass: "zXProject"
  // unitId: null
  // unitName: "基础医学部"
  // amountAlterationVO: [
  //   { adjustmentFee: null,//调整量
  //     afterFee: null,//调整后入账
  //     feeCardNum: "Z20250001",/经费卡号
  //     feeChargerId: "2c97a3549424ba180194251665790001",//经费卡负责人id
  //     feeChargerName: "老学生", //负责人
  //     incomeTotal: "1600000", //累计入账
  //     unitName: "基础医学部",所属单位
  //
  //   }
  // ],
})
// 定义一个方法用于打开弹窗
  const openDialog = () => {
    dialogVisible.value = true;

  };
// 控制弹窗显示与隐藏的变量
  const dialogVisible = ref(false);

// 处理所有调整量*10000
function multiplyBudgetFeeChangeBy10000(treeData) {
  if (!Array.isArray(treeData)) {
    return treeData;
  }

  treeData.forEach(item => {
    if (item.budgetFeeChange!== undefined) {
      item.budgetFeeChange = Number(item.budgetFeeChange) * 10000;
    }

    if (item.children && item.children.length > 0) {
      multiplyBudgetFeeChangeBy10000(item.children);
    }
  });

  return treeData;
}
//处理替换"alterationVals": [}里面 调整量	调整后入账额度
function replaceBudgetFeeChangeAndAfterAmountInAlterationVals(treeData) {
  if (!Array.isArray(treeData)) {
    return treeData;
  }

  treeData.forEach(item => {
    if (item.alterationVals && Array.isArray(item.alterationVals)) {
      item.alterationVals.forEach(alteration => {
        if (item.budgetFeeChange!== undefined) {
          alteration.budgetFeeChange = item.budgetFeeChange;
        }
        if (item.afterAmount!== undefined) {
          alteration.afterAmount = item.afterAmount;
        }
      });
    }

    if (item.children && Array.isArray(item.children)) {
      replaceBudgetFeeChangeAndAfterAmountInAlterationVals(item.children);
    }
  });

  return treeData;
}
function removeCircularReferences(obj, visited = new WeakSet()) {
  if (typeof obj!== 'object' || obj === null) {
    return obj;
  }
  if (visited.has(obj)) {
    return;
  }
  visited.add(obj);
  const newObj = Array.isArray(obj)? [] : {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (key === '$parent') {
        // 跳过 $parent 属性以避免循环引用
        continue;
      }
      newObj[key] = removeCircularReferences(obj[key], visited);
    }
  }
  return newObj;
}

// 提交按钮点击事件处理函数
const submit = () => {
  if(projectInfo.value.alterreason ==''){
    ElMessage({
      message: '请填写调账说明',
      type: 'error',
    })
    return
  }
  // 验证最外层节点调整量总和为0
  if (!validateTopLevelAdjustments()) {
    ElMessage({
      message: "调整量总和必须为0",
      type: "error"
    });
    return;
  }

  // // 验证最外层节点调整后入账额度等于累计入账
  // if (!validateTopLevelAfterAmount()) {
  //   ElMessage({
  //     message: "调账后入账总额度与累计入账额度不一致",
  //     type: "error"
  //   });
  //   return;
  // }
  //let lastVul =  treeData.value
  let cleanTreeData = removeCircularReferences(treeData.value);
  // let lastVul = replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(lastVul))
  let GoOut = {
    status:'1',
    //checkstatus:'-1',
    ...projectInfo.value,
    amountAlterationVO:[projectInfo.value],
    budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(cleanTreeData))
    // budgetAmountAlterationVO:multiplyBudgetFeeChangeBy10000(replaceBudgetFeeChangeAndAfterAmountInAlterationVals(treeData))
  }
  //afterAmount: 50000调整后入账
  // allincome: 50000 累计入账
  const incomeTotal = parseFloat(GoOut.incomeTotal);
  // if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
  //   ElMessage({
  //     message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
  //     type: 'error'
  //   });
  //   return;
  // }
  GoOut.id = ''
  loading.value = true
  add(GoOut)
      .then((res)=>{
        if (res.code == 200) {
          ElMessage({
            message: res.msg,
            type: 'success',
          })
          dialogVisible.value = false;
          emit('Getlist')
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
          })
        }
      })
      .finally(() => {
        loading.value = false // 结束加载
      })
  //   console.log('projectInfo',GoOut);
  // //  console.log('treeData',multiplyBudgetFeeChangeBy10000(treeData.value));
  //   console.log('treeData',treeData.value);//budgetFeeChange afterAmount

};
const emit = defineEmits(['Getlist'])
// 保存按钮点击事件处理函数
  const handleSave = () => {
  if(projectInfo.value.alterreason ==''){
    ElMessage({
      message: '请填写调账说明',
      type: 'error',
    })
    return
  }
    // 验证最外层节点调整量总和为0
    if (!validateTopLevelAdjustments()) {
      ElMessage({
        message: "调整量总和必须为0",
        type: "error"
      });
      return;
    }

    // // 验证最外层节点调整后入账额度等于累计入账
    // if (!validateTopLevelAfterAmount()) {
    //   ElMessage({
    //     message: "调账后入账总额度与累计入账额度不一致",
    //     type: "error"
    //   });
    //   return;
    // }
    //let lastVul =  treeData.value
    let cleanTreeData = removeCircularReferences(treeData.value);
        // let lastVul = replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(lastVul))
   let GoOut = {
      status:'-1',
      //checkstatus:'-1',
     ...projectInfo.value,
     amountAlterationVO:[projectInfo.value],
     budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(cleanTreeData))
    // budgetAmountAlterationVO:multiplyBudgetFeeChangeBy10000(replaceBudgetFeeChangeAndAfterAmountInAlterationVals(treeData))
   }
    //afterAmount: 50000调整后入账
    // allincome: 50000 累计入账
    const incomeTotal = parseFloat(GoOut.incomeTotal);
    if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
      ElMessage({
        message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
        type: 'error'
      });
      return;
    }
    GoOut.id = ''
    loading.value = true
    add(GoOut)
        .then((res)=>{
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            emit('Getlist')
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
        })
        .finally(() => {
          loading.value = false // 结束加载
        })
  //   console.log('projectInfo',GoOut);
  // //  console.log('treeData',multiplyBudgetFeeChangeBy10000(treeData.value));
  //   console.log('treeData',treeData.value);//budgetFeeChange afterAmount

  };

// 保存并通过按钮点击事件处理函数
  const handleSaveAndPass = () => {
    if(projectInfo.value.alterreason ==''){
      ElMessage({
        message: '请填写调账说明',
        type: 'error',
      })
      return
    }
    // 验证最外层节点调整量总和为0
    if (!validateTopLevelAdjustments()) {
      ElMessage({
        message: "调整量总和必须为0",
        type: "error"
      });
      return;
    }

    // // 验证最外层节点调整后入账额度等于累计入账
    // if (!validateTopLevelAfterAmount()) {
    //   ElMessage({
    //     message: "调账后入账总额度与累计入账额度不一致",
    //     type: "error"
    //   });
    //   return;
    // }
    //let lastVul =  treeData.value
    let cleanTreeData = removeCircularReferences(treeData.value);
    // let lastVul = replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(lastVul))
    let GoOut = {
      status:'2',
      //checkstatus:'2',
      ...projectInfo.value,
      amountAlterationVO:[projectInfo.value],
      budgetAmountAlterationVO: replaceBudgetFeeChangeAndAfterAmountInAlterationVals(multiplyBudgetFeeChangeBy10000(cleanTreeData))
      // budgetAmountAlterationVO:multiplyBudgetFeeChangeBy10000(replaceBudgetFeeChangeAndAfterAmountInAlterationVals(treeData))
    }
    //afterAmount: 50000调整后入账
   // allincome: 50000 累计入账
    const incomeTotal = parseFloat(GoOut.incomeTotal);
    if (GoOut.budgetAmountAlterationVO[0].allincome > GoOut.budgetAmountAlterationVO[0].afterAmount || GoOut.budgetAmountAlterationVO[0].afterAmount > incomeTotal) {
      ElMessage({
        message: '项目直接费用合计的累计入账额度应小于等于调整后入账额度，且调整后入账额度应小于等于累计入账',
        type: 'error'
      });
      return;
    }
    GoOut.id = ''
    loading.value = true
    add(GoOut)
        .then((res)=>{
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
            emit('Getlist')
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
        })
        .finally(() => {
          loading.value = false // 结束加载
        })
    //   console.log('projectInfo',GoOut);
    // //  console.log('treeData',multiplyBudgetFeeChangeBy10000(treeData.value));
    //   console.log('treeData',treeData.value);//budgetFeeChange afterAmount
  };
const handleInput = (inputValue) => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    // name:'项目新增'
    name:inputValue.data
  })
      .then((res) => {
        projectOptions.value = res.rows
      })
  //console.log('用户输入的值:', inputValue);
  // 在这里可以添加根据输入值调用其他函数的逻辑
  // 例如，根据输入值进行搜索、过滤等操作
};

// 验证最外层节点调整量总和为0
const validateTopLevelAdjustments = () => {
  const topLevelNodes = treeData.value;
  const totalAdjustment = topLevelNodes.reduce((sum, node) => {
    return sum + (node.budgetFeeChange || 0);
  }, 0);

  // 考虑浮点数精度问题，使用一个小的容差值
  return Math.abs(totalAdjustment) < 0.0001;
};

// 验证最外层节点调整后入账额度等于累计入账
const validateTopLevelAfterAmount = () => {
  const topLevelNodes = treeData.value;
  const totalAfterAmount = topLevelNodes.reduce((sum, node) => {
    return sum + (node.afterAmount || 0);
  }, 0);

  const incomeTotal = parseFloat(projectInfo.value.incomeTotal || 0);

  // 考虑浮点数精度问题，使用一个小的容差值
  return Math.abs(totalAfterAmount - incomeTotal) < 0.0001;
};

// 暴露 openDialog 方法供父组件调用
  defineExpose({
                 openDialog
               });
//所有弹窗内容end
</script>
<style scoped lang="scss">
.dialog-one-title{
  height: 30px;
  width: 100%;
  font-size: 16px;
  font-weight: bolder;
  border-bottom: 2px solid #ffce55;
}
.dialog-box > div{
  margin: 10px 0;
}
.title-col{
  color: #337AB7;
  font-weight: bolder;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>